""""
Part 1 is divided into three steps:

1- read the segmented astrocytic Image
2- Create the level set function smoothing the Segmented image
3- Compute Volume of astrocyte and compute the dimensionless parameter L

INPUT: astrocytic image 3D segmented
OUTPUT: level set function, background mesh, astrocytic mesh, dimensionless parameters

Package required: CutFEM library
""""



import numpy as np
from dolfin import *
from cutfem import *
from area_ls import compute_area, compute_surface
from timeit import default_timer as timer
from Create_ls import Image2levelset3D


import time

# String with date and time 
timestr = time.strftime("%d%m%Y")

# Start timer
startime_main = timer()

################################

# Step 1 read the astro  image #

################################

astro = np.load('Images/control_astro.npy')

astro[astro==255] = -1 # change the background pixels from 255 to -1


######################################################

# Step 2 Create the level set and background mesh   #

######################################################


bg_mesh, level_set, x_size, y_size, z_size, nx, ny, nz, image_f = Image2levelset3D(astro)

np.save('./results_'+ timestr +'/mesh_sizes.npy', np.asarray([x_size, y_size, z_size]))


h = bg_mesh.hmax()
File("./results_"+ timestr +"/bgmesh.pvd") << bg_mesh;


# Extract fictitious domain mesh

mesh = CutFEMTools_fictitious_domain_mesh(bg_mesh,level_set,0,0);

File("./results_"+ timestr +"/mesh_astro.pvd") << mesh;


#############################
#  SAVE bg_mesh and level set
#############################

Hdf = HDF5File(bg_mesh.mpi_comm(), 'hdfFile', "w")
Hdf.write(bg_mesh, "bg_mesh")
Hdf.write(level_set, "level_set")

###############################

# Step 4 Compute Volume of astro

###############################

volume = compute_area(bg_mesh, level_set, Constant(1.))
print('volume dimensionless', volume)
np.save('./results_'+ timestr +'/Volume.npy', volume)

original_astro_volume = 3673.
L = np.cbrt(original_astro_volume/volume)
print('dimensionless parameter L', L)

np.save('./results_'+ timestr +'/L.npy', L)

surface = compute_surface(bg_mesh, level_set)
print('surface dimensionless', surface)